// pages/category/index.js
import { getCategoryList } from '../../api/index'
import { strToObject, objectToSearh } from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cateList: [],//分类列表
    cateSeList: [],//二级分类列表
    cateThirdList: [],//三级分类列表
    goodsList: [],//当前分类下商品列表
    cateSeId: '',//当前选中的分类ID
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 1-获取分类列表
    getCategoryList().then(res => {
      // 1-1空值判断
      const data = res.data ? res.data : []
      // 1-2首页只抽取二级分类标签
      let cateSeList = data.filter(v => v.level === 2)
      cateSeList.forEach(v => { v.remark = strToObject(v.remark) })
      this.setData({
        cateList: data,
        cateSeList,
        cateSeId: cateSeList[0].id
      }, () => {
        this.getCateThirdList()
      })
    })
  },
  // 2-获取二级分类下三级分类列表
  getCateThirdList() {
    const { cateList, cateSeId } = this.data
    let cateThirdList = cateList.filter(v => v.pid === cateSeId)
    // 2-1将level=4数据填充到对应的level=3的children中
    cateThirdList = cateThirdList.reduce((pre, cur) => {
      let arrList = cateList.filter(v => v.pid === cur.id)
      pre.push({ children: arrList, ...cur })
      return pre
    }, [])
    this.setData({ cateThirdList })
  },
  // 切换左侧类别
  handleClick(e) {
    const cateSeId = e.currentTarget.dataset.cateid
    this.setData({ cateSeId }, () => {
      this.getCateThirdList()
    })
  },
  // 跳转商品列表页面
  goGoodsList(e) {
    const { nextcateid, nextcatename } = e.currentTarget.dataset
    const params = {
      cateid: nextcateid,
      catename: nextcatename
    }
    wx.navigateTo({
      url: '/pages/goods_list/index' + objectToSearh(params)
    })
  }
})